//
//  WBRefreshView.swift
//  XLWibo-Swift
//
//  Created by 王林 on 2016/11/19.
//  Copyright © 2016年 木木. All rights reserved.
//

enum RefreshStatue:Int {
    case Normal = 0
    case Already
    case Refreshing
}

import UIKit
let refreshHight:CGFloat = 60

class WBRefreshView: UIControl {
    
    var status:RefreshStatue = .Normal{
        didSet{
            
            switch status {
            case .Normal:  //下拉刷新
                lblPull.text = "下拉刷新"
                arrowView.isHidden = false
                indicator.stopAnimating()
                UIView.animate(withDuration: 0.25, animations: { 
                    self.arrowView.transform = CGAffineTransform.identity
                })
                if  oldValue == .Refreshing {
                    UIView.animate(withDuration: 0.25, animations: { 
                        self.scrollerView!.contentInset.top = self.scrollerView!.contentInset.top - refreshHight
                    })
                }
                
            case .Already:  //下拉刷新
                lblPull.text = "🐿,刷新了"
                UIView.animate(withDuration: 1.0, animations: {
                    self.arrowView.transform = CGAffineTransform.init(rotationAngle: CGFloat(M_PI ))
                })
                
            case .Refreshing:  //下拉刷新
                lblPull.text = "正在刷新..."
                indicator.startAnimating()
                arrowView.isHidden = true
                //MARK:
                // MARK: - 发送事件
                sendActions(for: .valueChanged)
                UIView.animate(withDuration: 0.25, animations: {
                    self.scrollerView!.contentInset.top = self.scrollerView!.contentInset.top + refreshHight
                })
                
                
            }
        }
    }
    

    override init(frame: CGRect) {
        let rect = CGRect(x: 0, y: -refreshHight, width: USC_width, height: refreshHight)
        super.init(frame: rect)
//        self.backgroundColor = randomColor()
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //kvo 监听
    override func willMove(toSuperview newSuperview: UIView?) {
        if let fatherView = newSuperview as? UIScrollView {
           self.scrollerView = fatherView
            self.scrollerView?.addObserver(self, forKeyPath: "contentOffset", options: [.new], context: nil)
        }
    }
    //实现监听方法
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        
        let offsetY = self.scrollerView?.contentOffset.y ?? 0
        let targertY = -(self.scrollerView!.contentInset.top + refreshHight)
        
        if scrollerView!.isDragging {
            if  status == .Normal && offsetY < targertY {
                //准备状态
                status = .Already
              
            }
            else if  status == .Already && offsetY > targertY  {
                //下拉状态(默认状态)
                status = .Normal
            }
        }else{
            //用户拖拽  和状态是准备状态时 才会触发刷新
            if status == .Already {
                status = .Refreshing
            }
        }
    }
    
    //停止刷新
    func endRefreshing(){
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5, execute: {
            self.status = .Normal
        })
    }
    
    

    func setupUI(){
        //长腿(图片)
        self.addSubview(imgView)
        self.addSubview(arrowView)
        self.addSubview(lblPull)
        self.addSubview(indicator)
       //腿
        imgView.snp.makeConstraints { (make) in
            make.trailing.leading.bottom.equalTo(self)
        }
       //箭头
        arrowView.snp.makeConstraints { (make) in
            make.centerX.equalTo(self).offset(-20)
            make.centerY.equalTo(self)
        }
         //文字
        lblPull.snp.makeConstraints { (make) in
            make.centerY.equalTo(self)
            make.centerX.equalTo(self).offset(15)
        }
        //菊花
        indicator.snp.makeConstraints { (make) in
            make.center.equalTo(self)
        }
        
    }
    

    private   lazy var imgView: UIImageView = UIImageView.init(image: #imageLiteral(resourceName: "refreshbg"))
    private  lazy var arrowView:UIImageView = UIImageView.init(image: #imageLiteral(resourceName: "tableview_pull_refresh"))
    private  lazy var lblPull: UILabel = UILabel(title: "下拉起飞", titleColor: UIColor.orange, font: UIFont.systemFont(ofSize: 15))
    private  lazy var indicator:UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .gray)
    var scrollerView:UIScrollView?
    
    deinit {
        self.scrollerView?.removeObserver(self, forKeyPath: "contentOffset")
    }
    
    
    
    
}











